package com.boomsecret.nio.simple;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class ServerDemo  {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(11111));

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            int count = selector.select(2000);
            if (count > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()) {
                        ServerSocketChannel tempServerChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = tempServerChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(5);
                        int read = 1;
                        StringBuilder sb = new StringBuilder();
                        while ((read = socketChannel.read(byteBuffer)) > 0) {
                            sb.append(new String(byteBuffer.array(), 0, read));
                            byteBuffer.clear();
                        }
                        socketChannel.close();
                        System.out.println("服务收到的数据为：" + sb.toString());
                    }
                    iterator.remove();
                }
            }
        }
    }
}
